package bg.code.commons.builder.utils;

import bg.code.commons.builder.vo.ColumnDescriptor;
import bg.code.commons.builder.vo.TableDescriptor;
import com.intellij.lang.jvm.annotation.JvmAnnotationAttribute;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.impl.source.tree.java.PsiNameValuePairImpl;

import java.util.List;
import java.util.Optional;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/3/18
 * 描述：
 */
public class JavaTableUtil {
    private static final String COMMENT = "org.nutz.dao.entity.annotation.Comment";
    private static final String TABLE = "org.nutz.dao.entity.annotation.Table";

    /***
     * 获取注释
     * @author zxq(956607644 @ qq.com)
     * @date 2020/3/18 16:37
     * @param clzss

     * @return java.lang.String
     */
    public static String getComment(PsiClass clzss) {

        PsiAnnotation annotation = clzss.getAnnotation(COMMENT);
        if (annotation != null) {
            List<JvmAnnotationAttribute> attributes = annotation.getAttributes();
            if (attributes.size() > 0) {
                return ((PsiNameValuePairImpl) attributes.get(0)).getLiteralValue();
            }
        }
        return "";
    }

    /***
     * 获取ing
     * @author zxq(956607644 @ qq.com)
     * @date 2020/3/18 16:37
     * @param clzss

     * @return java.lang.String
     */
    public static String getTableName(PsiClass clzss) {

        PsiAnnotation annotation = clzss.getAnnotation(TABLE);
        if (annotation != null) {
            List<JvmAnnotationAttribute> attributes = annotation.getAttributes();
            if (attributes.size() > 0) {
                return ((PsiNameValuePairImpl) attributes.get(0)).getLiteralValue();
            }
        }
        return "";
    }

    public static TableDescriptor getTableData(PsiClass clzss, List<ColumnDescriptor> javaFields) {
        TableDescriptor tableDescriptor = new TableDescriptor();
        tableDescriptor.setEntityName(clzss.getName());
        tableDescriptor.setComment(getComment(clzss));
        tableDescriptor.setName(getTableName(clzss));
        tableDescriptor.setUuid(false);
        tableDescriptor.setUuid(false);
        tableDescriptor.setLabel(tableDescriptor.getComment());
        Optional optional = javaFields.stream().filter(ColumnDescriptor::isPrimaryKey).findFirst();
        if (optional.isPresent()) {
            ColumnDescriptor field = (ColumnDescriptor) optional.get();
            tableDescriptor.setPrimaryKey(field.getColumnName());
            if (TableDescriptor.UUID_COLUMN.equals(field.getColumnName().toLowerCase())) {
                tableDescriptor.setUuid(true);
            }
        }
        return null;
    }
}
